import React, { useState, useEffect } from 'react';
import { Select } from '@arco-design/web-react';
import styles from './index.module.scss';
import { getVideoApiOptions } from '@/api/video';
import { useCallback } from 'react';

// 默认的下拉选项配置
export const DEFAULT_OPTIONS = {
  // 视频时长选项
  duration: [
    { value: 'short', label: '5s' },
    { value: 'long', label: '10s' },
  ],
  // 视频分辨率选项
  resolution: [
    // { value: '720p', label: '720p' },
    { value: '1080p', label: '1080p' },
  ],
  // 视频比例选项
  ratio: [
    { value: '16:9', label: '16:9' },
    { value: '9:16', label: '9:16' },
    { value: '1:1', label: '1:1' },
  ],
  // 视频模型选项
  deviceApi: [],
};

/**
 * 视频配置选择器组件
 * 支持静态选项配置和动态接口获取选项
 */
const VideoSelectConfig = ({
  // 当前值
  duration = undefined,
  resolution = undefined,
  ratio = undefined,
  deviceApi = undefined,
  // 值变化回调
  onDurationChange,
  onResolutionChange,
  onRatioChange,
  onDeviceApiChange,
  // 自定义选项配置
  options = {},
  // 动态获取选项的函数
  fetchOptions = null,
  // 是否显示生成按钮
  showGenerateButton = true,
  // 生成按钮点击回调
  onGenerate,
  // 自定义样式类名
  className = '',
  // 视频场景
  scene = 'text2video',
}) => {
  // 内部选项状态，用于支持动态获取
  const [internalOptions, setInternalOptions] = useState({ ...DEFAULT_OPTIONS });
  // 加载状态
  const [loading, setLoading] = useState(false);

  // 合并用户提供的选项和默认选项
  const mergedOptions = {
    ...internalOptions,
    ...options,
  };

  const changeDeviceApi = useCallback(
    value => {
      console.log(value);
      // 这是需要把deviceApi的value label都传过去
      const selectedOption = mergedOptions.deviceApi.find(option => option.value === value);
      console.log('changeDeviceApi', selectedOption);
      if (selectedOption) {
        value = {
          value: selectedOption.value,
          label: selectedOption.name,
        };
      }
      onDeviceApiChange?.(value);
    },
    [onDeviceApiChange, mergedOptions.deviceApi]
  );

  // 组件挂载时，如果提供了fetchOptions函数，则调用它获取选项
  useEffect(() => {
    if (fetchOptions && typeof fetchOptions === 'function') {
      const loadOptions = async () => {
        try {
          setLoading(true);
          const fetchedOptions = await fetchOptions();
          if (fetchedOptions) {
            setInternalOptions(prev => ({ ...prev, ...fetchedOptions }));
          }
        } catch (error) {
          console.error('获取视频配置选项失败:', error);
          // 出错时保持原有选项不变
        } finally {
          setLoading(false);
        }
      };

      loadOptions();
    }
  }, [fetchOptions]);

  useEffect(() => {
    // 调用接口去查询 deviceApi 下拉列表
    if (duration && ratio && resolution) {
      getVideoApiOptions({ duration, aspectRatio: ratio, resolution, scene: scene }).then(res => {
        if (res.code === 200) {
          setInternalOptions(prev => ({ ...prev, deviceApi: res?.data }));

          // 检查当前选中的deviceApi是否在更新后的选项中且为disabled状态
          if (deviceApi && res?.data) {
            const currentOption = res.data.find(option => option.value === deviceApi);
            if (currentOption?.disabled) {
              // 如果当前选中的选项是disabled状态，则清空选中值
              onDeviceApiChange?.({ value: undefined, label: '' });
            }
          }
        }
      });
    }
  }, [duration, ratio, resolution]);

  return (
    <div className={`${styles.container} ${className}`}>
      <div className={styles.selectSection}>
        <Select
          className={styles.select}
          value={duration}
          placeholder="请选择"
          onChange={onDurationChange}
          loading={loading}>
          {mergedOptions.duration?.map(option => (
            <Select.Option key={option.value} value={option.value}>
              {option.label}
            </Select.Option>
          )) || []}
        </Select>
        <Select
          className={styles.select}
          placeholder="请选择"
          value={resolution}
          onChange={onResolutionChange}
          loading={loading}>
          {mergedOptions.resolution?.map(option => (
            <Select.Option key={option.value} value={option.value}>
              {option.label}
            </Select.Option>
          )) || []}
        </Select>
        {
          <Select
            className={styles.select}
            value={ratio}
            placeholder={'请选择'}
            onChange={onRatioChange}
            disabled={scene === 'start-end2video'}
            loading={loading}>
            {scene !== 'start-end2video' ? (
              mergedOptions.ratio?.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              )) || []
            ) : (
              <Select.Option key="自动匹配" value={'16:9'}>
                自动匹配
              </Select.Option>
            )}
          </Select>
        }
        <Select
          className={styles.select}
          value={deviceApi}
          placeholder="请选择"
          onChange={changeDeviceApi}
          loading={loading}>
          {mergedOptions.deviceApi?.map(option => (
            <Select.Option key={option.value} value={option.value} disabled={option.disabled}>
              {option.name}
            </Select.Option>
          )) || []}
        </Select>
      </div>

      {showGenerateButton && (
        <button className={styles.generateButton} onClick={onGenerate} disabled={loading}>
          立即生成
        </button>
      )}
    </div>
  );
};

export default VideoSelectConfig;
